package org.knight.gearbox.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipBuilder {
    private String baseFolder = System.getProperty("java.io.tmpdir");

    private Logger logger = LoggerFactory.getLogger(getClass());

    // public void createZipFile(File dir) {
    //     String pp1 = "I'm pp1";
    //     String pp2 = "I'm pp2";
    //     String fileName = baseFolder + "test.zip";
    //     try (ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(fileName))) {

    //         ZipEntry entry = new ZipEntry("a");

    //         outputStream.putNextEntry(entry);
    //         outputStream.closeEntry();

    //         ZipEntry entry1 = new ZipEntry("a/pp1.txt");
    //         outputStream.putNextEntry(entry1);
    //         outputStream.write(pp1.getBytes());
    //         outputStream.closeEntry();

    //         ZipEntry entry2 = new ZipEntry("b");

    //         outputStream.putNextEntry(entry2);
    //         outputStream.closeEntry();

    //         ZipEntry entry3 = new ZipEntry("b/pp2.txt");
    //         outputStream.putNextEntry(entry3);
    //         outputStream.write(pp2.getBytes());
    //         outputStream.closeEntry();

    //     } catch (IOException e) {
    //         logger.warn("", e);
    //     }
    // }


    public void createZipFile(Map<String, InputStream> files, Function<File,Object> callback) {
        String fileName = baseFolder + UUID.randomUUID().toString() +".zip";
        File file = new File(fileName);
        try (ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(file))) {
            files.entrySet()
                    .stream()
                    .forEach(entry -> {
                        writeZipEntry(outputStream, entry);
                    });
            outputStream.flush();
        } catch (Exception e) {
            logger.warn("error create zip file", e);
        }
        callback.apply(file);
    }

    private void writeZipEntry(ZipOutputStream outputStream, Map.Entry<String, InputStream> entry) {
        ZipEntry zipEntry = new ZipEntry(entry.getKey());
        try {
            outputStream.putNextEntry(zipEntry);
            InputStream inputStream = entry.getValue();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.closeEntry();
        } catch (IOException e) {
            logger.warn("exception create entry" + entry.getKey(), e);
        }
    }
}
